<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$props.title"
    width="80%"
    :before-close="handleDialogClose"
  >
    <div class="content">
      <el-form
        :model="innerQueryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <el-form-item label="搜索学员" prop="name">
          <el-input
            v-model="innerQueryParams.name"
            placeholder="请输入学员姓名或手机号"
            clearable
            style="width: 240px"
            @keyup.enter="getInnerList"
          />
        </el-form-item>
        <el-form-item label="消耗方式" prop="courseId">
          <el-select
            v-model="innerQueryParams.courseId"
            placeholder="请选择消耗方式"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.state === '1' ? item.name + '(已停用)' : item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在班级" prop="classId">
          <el-select
            v-model="innerQueryParams.classId"
            placeholder="请选择所在班级"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.beOver === '0' ? item.name + '(已结业)' : item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="getInnerList"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="innerList"
        :row-key="(row) => row.studentId"
        ref="innerTable"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          reserve-selection
          width="55"
          align="center"
          :selectable="selectable"
        />
        <el-table-column label="序号" width="55" align="center">
          <template #default="scope">
            <span>{{
              (innerQueryParams.pageNum - 1) * innerQueryParams.pageSize +
              scope.$index +
              1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学员名称" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile" />
        <el-table-column label="消耗方式" align="center" prop="courseName" />
        <el-table-column label="剩余额度" align="center" prop="num">
          <template #default="scope">{{ scope.row.num + "课时" }}</template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="innerQueryParams.pageNum"
        v-model:limit="innerQueryParams.pageSize"
        @pagination="getInnerList"
        size="small"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <div style="float: left">已选择：{{ items.length }}人</div>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  addMumberAPI,
  studentCourseListAPI,
  addTempMemberAPI,
} from "@/api/registrar/class";
import { getCourseListAPI } from "@/api/registrar/course";
import { getClassListAPI } from "@/api/registrar/class";

const props = defineProps({
  title: {
    type: String,
  },
  // 关联课程id,多个用逗号分隔
  courseFilterIds: {
    type: String,
  },
  classId: {
    type: String,
  },
  isVip: {
    type: String,
  },
  data: {
    type: Object,
    default: () => {
      return {
        orderNo: null,
        cofId: null,
      };
    },
  },
  from: {
    type: String,
    default: "default",
  },
});

// 变量--------------------------------------------------------------------------------------------------------------------
const { proxy } = getCurrentInstance();

const emits = defineEmits(["refreshPage"]);
const { sys_user_sex } = proxy.useDict("sys_user_sex"); // 0男 1女 2未知
const loading = ref(false);
const dialogVisible = ref(false);
const innerTable = ref(null);
const innerList = ref([]);
const showSearch = ref(true);
const total = ref(0);
const items = ref([]);

const courseList = ref([]);
const classList = ref([]);

const data = reactive({
  innerQueryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
    courseId: undefined,
    classId: undefined,
    mobile: "",
  },
});

const { innerQueryParams } = toRefs(data);

function selectable(row) {
  const selectedSIds = items.value.map((obj) => obj.studentId); //被选中的studentId数组
  const selectedIds = items.value.map((obj) => obj.courseId); //被选中的id数组
  return (
    !selectedSIds.includes(row.studentId) || selectedIds.includes(row.courseId)
  );
}

function openSelector() {
  getClassList();
  getCourseFilterList();
  resetInnerData();
  getInnerList();
  dialogVisible.value = true;
}

function handleDialogClose() {
  dialogVisible.value = false;
}

function handleSelectionChange(selection) {
  items.value = selection;
}

function resetInnerData() {
  innerQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: "",
    courseId: undefined,
    classId: undefined,
    mobile: "",
  };
  innerTable.value && innerTable.value.clearSelection();
}

function resetQuery() {
  resetInnerData();
  getInnerList();
}

function getInnerList() {
  innerList.value = [];
  loading.value = true;
  if (props.from === "rollCall") {
    studentCourseListAPI({
      ...innerQueryParams.value,
      idsStr: props.courseFilterIds, // 通过关联课程，筛选出消耗方式为关联课程的课程列表
      orderNo: props.data.orderNo, // 当前班级，用于过滤掉已被添加在此班级的学员
    }).then((response) => {
      innerList.value = response.rows;
      loading.value = false;
      total.value = response.total;
    });
  } else {
    studentCourseListAPI({
      ...innerQueryParams.value,
      idsStr: props.courseFilterIds, // 通过关联课程，筛选出消耗方式为关联课程的课程列表
      classIdM: props.classId, // 当前班级，用于过滤掉已被添加在此班级的学员
    }).then((response) => {
      innerList.value = response.rows;
      loading.value = false;
      total.value = response.total;
    });
  }
}

// 添加成员
function handleSubmit() {
  loading.value = true;
  let arr = [];
  let studentIdArr = [];
  items.value.forEach((i) => {
    i.consumeCourseId = i.courseId;
    i.classId = props.classId;
    arr.push({ id: i.studentId, courseId: i.courseId });
    studentIdArr.push(i.studentId);
  });
  if (props.from === "rollCall") {
    addTempMemberAPI({
      ids: arr,
      cofId: props.data.cofId,
      orderNo: props.data.orderNo,
      classDate: props.data.classDate,
      temp: 0, // 0临时学员1正常学员 2补课学员
    }).then((response) => {
      //classList.value = response.rows;
      loading.value = false;
      dialogVisible.value = false;
      refreshParent(studentIdArr);
    });
  } else {
    addMumberAPI(items.value).then((response) => {
      //classList.value = response.rows;
      loading.value = false;
      dialogVisible.value = false;
      refreshParent(studentIdArr);
    });
  }
}

// 关联课程
function getCourseFilterList() {
  getCourseListAPI({
    pageSize: 9999,
    pageNum: 1,
    //state: "0",
    idsStr: props.courseFilterIds,
    lessonType: props.isVip,
  }).then((response) => {
    courseList.value = response.rows;
    loading.value = false;
  });
}

function getClassList() {
  loading.value = true;
  getClassListAPI({
    pageSize: 9999,
    pageNum: 1,
    isVip: props.isVip,
  }).then((response) => {
    classList.value = response.rows;
    loading.value = false;
  });
}

function refreshParent(studentIdArr) {
  emits("refreshPage", studentIdArr);
}

defineExpose({ openSelector }); // 用于父组件调用
</script>

<style lang="scss" scoped>
:deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
